##########################
# ANALYSIS FUNCTIONS #####
#
# Replication Material for:
# Continuity or Change? (In)direct Rule in British and French Colonial Africa
# 
# Carl Mueller-Crepon, 2020
# International Organization
#
# File Description:
# This file containes auxiliary functions called during the analysis.
#
# Called from the main analysis files
#
##########################



# Add line to latex table
latex.addline <- function(title,entries){c(title,paste0("\\multicolumn{1}{c}{",entries,"}"))}
latex.addline_nomc <- function(title,entries){c(title,entries)}
latex.any.row <- latex.addline

# Improved stargazer note function
nice_notes <- function(note){
  paste("\\begin{minipage}[t]{0.8\\columnwidth}",
        paste(note, collapse = " "),
        "\\end{minipage}")
}


# Mean of dependent variable for latex table
latex.mean.dv <- function(model.ls){
  c("Mean DV:",paste0("\\multicolumn{1}{c}{",signif(unlist(lapply(model.ls, function(m){
    if(any(names(m) == "response")){
      mean(m$response)
    } else {
      mean(m@resp$y)
    }
    })), 2),"}"))
}

# SD of dependent variable for latex table
latex.mean.sd <- function(model.ls){
  c("Std.-dev. DV:",paste0("\\multicolumn{1}{c}{",signif(unlist(lapply(model.ls, function(m){sd(m$response)})), 2),"}"))
}

# Extract all coefficients from a list of felm models
extract_coef <- function(m.list){
  lapply(m.list, function(m){
    list(dv = colnames(m$coefficients),
         coef = m$coefficients,
         clustervcv = m$clustervcv)
  })
}

# Helper function to combine regression specification
make_form <- function(dv, expl, fe, iv = "0", se = "0" ){
  as.formula(paste(dv, "~", paste(expl, collapse = "+"), "|",
                   paste(fe, collapse = "+"), "|", iv, "|", se))
}

# Generate Regression weights
gen_weights <- function(vec){
  tab <- table(vec)
  weights <- data.frame(cbind(weight = as.numeric(tab), unit = as.character(names(tab))),
                        stringsAsFactors = F)
  weight.vec <- 1/as.numeric(join(data.frame(unit = as.character(vec), stringsAsFactors = F),
                                  weights, type = "left", by = "unit")[,2])
  return(weight.vec)
  
}

# Make coefficients with SE to nice text
effect_text <- function(coef, se, trans_fun = NULL, accuracy = 1){
  if(is.null(trans_fun)){
    paste0(signif(coef,accuracy),
           " [", signif(coef - se*1.95,accuracy),", ", 
           signif(coef + se*1.95,accuracy), "]")
  } else {
    paste0(signif(trans_fun(coef),accuracy),
           " [", signif(trans_fun(coef - se*1.95),accuracy),", ", 
           signif(trans_fun(coef + se*1.95),accuracy), "]")
  }
}


# Make stargazer columnlabels with one extra layer and rulers
collab_w_ruler <- function(column.labels, column.separate, trim = 10, add.below = NULL){
  cmidrule <- paste(paste0("\\cmidrule(lr{",trim,"pt}){", c(2, 2 + cumsum(column.separate[-length(column.separate)])), "-",
                           c(1+ cumsum(column.separate)), "}"), collapse = " ")
  if(is.null(add.below)){
    result <-  c(column.labels[-length(column.labels)], 
                 paste0(column.labels[length(column.labels)], "} \\\\ ", cmidrule, " \\\\[-6ex] {"))
  } else {
    add.b <- paste(paste0(" & \\multicolumn{1}{c}{", add.below, "}"), collapse = "")
    result <-  c(column.labels[-length(column.labels)], 
                 paste0(column.labels[length(column.labels)], "} \\\\ ", cmidrule, add.b, " {"))
  }
  
  return(result)
}
